package com.wcpdoc.exam.core.service.impl;

import com.wcpdoc.core.dao.BaseDao;
import com.wcpdoc.core.entity.PageResult;
import com.wcpdoc.core.entity.PageResultEx;
import com.wcpdoc.core.service.impl.BaseServiceImp;
import com.wcpdoc.exam.core.dao.QuestionTypeDao;
import com.wcpdoc.exam.core.dao.UserQuestionTypeDao;
import com.wcpdoc.exam.core.entity.QuestionType;
import com.wcpdoc.exam.core.entity.UserQuestionType;
import com.wcpdoc.exam.core.service.UserQuestionTypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserQuestionTypeServiceImpl extends BaseServiceImp<UserQuestionType> implements UserQuestionTypeService {
    @Resource
    private UserQuestionTypeDao userQuestionTypeDao;
    @Resource
    private QuestionTypeDao questionTypeDao;

    @Override
    @Resource(name = "userQuestionTypeDaoImpl")
    public void setDao(BaseDao<UserQuestionType> dao) {
        super.dao = dao;
    }


    /**
     * 设置某题库有权限的人
     *  1.先删除，再重新添加
     * @param questionTypeId
     * @param userIdList
     * @param updateUserId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageResult setting(Integer questionTypeId, List<Integer> userIdList, Integer updateUserId) {
        QuestionType type = questionTypeDao.getEntity(questionTypeId);
        if(type==null){
            return PageResultEx.err().msg("题库不存在");
        }
        userQuestionTypeDao.deleteByQuestionTypeId(questionTypeId);
        for (Integer userId : userIdList) {
            UserQuestionType userQuestionType=  new UserQuestionType();
            userQuestionType.setQuestionTypeId(questionTypeId);
            userQuestionType.setUserId(userId);
            userQuestionType.setUpdateTime(new Date());
            userQuestionType.setUpdateUserId(updateUserId);
            userQuestionType.setState(1);
            add(userQuestionType);
        }
        return PageResultEx.ok().msg("设置成功");
    }

    /**
     * 获取某题库有权限的人ID
     *
     * @param questionTypeId
     * @return
     */
    @Override
    public PageResult getUserListByQuestionTypeId(Integer questionTypeId) {
        final List<Map<String,Object>> userList = userQuestionTypeDao.getUserByQuestionTypeId(questionTypeId);
        return PageResultEx.ok().data(userList);
    }
}
